<script setup>
import {defineAsyncComponent, ref} from "vue";
import {router} from "@inertiajs/vue3";
import {route} from "ziggy-js";
import useTable from "@/composables/useTable";
import useRequest from "@/composables/useRequest.js";
import {Message} from "@arco-design/web-vue";
import AppPage from "@/pages/admin/layouts/AppPage.vue";
import RangeDate from "@/components/RangeDate.vue";

const FormPopup = defineAsyncComponent(() => import('./components/FormPopup.vue'));

const props = defineProps({
    data: {
        type: Array,
        default: () => []
    },
    pagination: {
        type: Object,
        default: () => ({
            current: 1,
            pageSize: 10,
            total: 0,
            showTotal: true
        })
    },
    roleOptions: {
        type: Array,
        default: () => []
    },
    filters: {
        type: Object,
        default: () => ({
            keyword: '',
            startDate: '',
            endDate: '',
            page: 1,
        }),
    },
    title: {
        type: String,
        default: () => '用户管理',
    }
})
const loading = ref(false);
const searchLoading = ref(false);

const params = ref({
    keyword: '',
    startDate: '',
    endDate: '',
    page: 1,
})

const {TableRef, bordered, scroll} = useTable()
const {deleteApi} = useRequest('admin.setting.users')

const handleSearch = (resetPage = true) => {
    if (resetPage) {
        params.value.page = 1;
    }
    loading.value = true;
    searchLoading.value = true;
    // 过滤空值参数
    const filteredParams = Object.fromEntries(
        Object.entries(params.value).filter(([_, value]) =>
            value !== '' && value !== null && value !== undefined
        )
    );

    router.get(route('admin.setting.users.index'), filteredParams, {
            replace: true,
            preserveState: true, // 保留其他状态
            onFinish: () => {
                loading.value = false;
                searchLoading.value = false;
            }
        }
    )
}

const handleQuickSearch = () => {
    if (!params.value.keyword.trim()) {
        Message.warning('请输入搜索关键词');
        return;
    }
    handleSearch();
}
const handleReset = () => {
    params.value = {
        keyword: '',
        startDate: '',
        endDate: '',
        page: 1,
    }
    handleSearch()
}

const handlePageChange = (page) => {
    params.value.page = page
    handleSearch()
}

const formPopupRef = ref()
const handleAdd = () => formPopupRef.value?.add()
const handleEdit = (id) => formPopupRef.value?.edit(id)
const handleDelete = async (id) => {
    await deleteApi(id)
    router.reload()
    Message.success('删除成功')
}

onMounted(() => {
    params.value = {
        ...params.value,
        ...props.filters
    }
})
</script>

<template>
    <app-page :breadcrumbs :title>
        <a-card
            :body-style="{ padding: '0' }"
            :header-style="{ padding: '16px 20px', borderBottom: '1px solid #f0f0f0' }"
            :style="{ borderRadius: '8px', overflow: 'hidden' }"
            :title="title"
            class="custom-card shadow-sm transition-all duration-300 hover:shadow-md"
        >

            <!-- 顶部搜索栏 -->
            <div class="p-4 border-b border-gray-100 bg-gray-50">
                <div class="flex flex-wrap items-end gap-4">
                    <!-- 关键词搜索 -->
                    <div class="flex-1 min-w-[180px]">
                        <a-input
                            v-model="params.keyword"
                            allow-clear
                            placeholder="请输入用户名或者手机号"
                            @clear="handleSearch"
                            @press-enter="handleQuickSearch"
                        />
                    </div>

                    <div class="w-[240px]">
                        <RangeDate
                            v-model:end="params.endDate"
                            v-model:start="params.startDate"
                        />
                    </div>


                    <!-- 操作按钮 -->
                    <div class="flex gap-2">
                        <a-button type="primary" @click="handleSearch">
                            <template #icon>
                                <icon-search/>
                            </template>
                            搜索
                        </a-button>

                        <a-button @click="handleReset">
                            重置
                        </a-button>
                    </div>
                </div>
            </div>

            <!-- 操作栏 -->
            <div class="p-3 bg-white border-b border-gray-100">
                <div class="flex flex-wrap items-center justify-between gap-3">
                    <a-button type="primary" @click="handleAdd"> 新增账号</a-button>
                </div>
            </div>

            <div class="p-4">
                <a-table
                    ref="TableRef"
                    :bordered
                    :data="data"
                    :pagination
                    :scroll
                    :scrollbar="false"
                    :table-layout-fixed="true"
                    column-resizable
                    row-key="id"
                    @page-change="handlePageChange"
                >
                    <template #columns>
                        <a-table-column :width="60" align="left" data-index="id" title="#"/>
                        <a-table-column :width="200" data-index="name" title="账号信息">
                            <template #cell="{ record }">
                                <div class="flex items-center gap-2">
                                    <a-avatar :size="42">
                                        <img :src="record.avatar" alt="">
                                    </a-avatar>
                                    <div class="flex flex-col gap-2">
                                        <span class="text-sm"> {{ record.name }}</span>
                                        <span class="text-sm"> {{ record.phone }}</span>
                                    </div>
                                </div>
                            </template>
                        </a-table-column>
                        <a-table-column :width="80" data-index="gender" title="性别">
                            <template #cell="{ record }">
                                <a-badge :color="record.gender === 1 ? 'green' : 'red'"
                                         :text=" record.gender === 1 ? '男' : '女'"/>
                            </template>
                        </a-table-column>
                        <a-table-column :width="120" data-index="role" title="角色"/>
                        <a-table-column :width="120" data-index="status" title="状态">
                            <template #cell="{ record }">
                                <a-badge :color="record.status === 1 ? 'green' : 'red'"
                                         :text=" record.status === 1 ? '正常' : '禁用'"/>
                            </template>
                        </a-table-column>
                        <a-table-column :width="120" data-index="created_at" title="创建时间"/>
                        <a-table-column :width="140" data-index="last_login_ip" title="登录IP"/>
                        <a-table-column :width="180" data-index="last_login_at" title="登录时间"/>
                        <a-table-column :width="120" fixed="right" title="操作">
                            <template #cell="{ record }">
                                <a-space>
                                    <a-link @click="handleEdit(record.id)"> 编辑</a-link>
                                    <a-popconfirm
                                        content="您确定要删除该项吗?"
                                        type="warning"
                                        @ok="() => handleDelete(record.id)"
                                    >
                                        <a-link status="danger"> 删除</a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>

            </div>
            <form-popup ref="formPopupRef" @success="router.reload()"/>
        </a-card>
    </app-page>
</template>

<style scoped>

</style>
